﻿#-------------------------------------------------------------------------------
# Name:        ImageRecognizer
# Purpose:
#
# Author:      evob0413
#
# Created:     11.07.2014
# Copyright:   (c) evob0413 2014
# Licence:     <your licence>
#-------------------------------------------------------------------------------
import os
import hashlib
import time
from PIL import Image
from operator import itemgetter
from VectorCompare import VectorCompare
from InformationGatheringConstants import *

class ImageRecognizer(object):

    def recognize_text(self, image_key, image):
        image = image.convert("P")
        histogram = image.histogram()

        #print image.format, image.size, image.mode
        #print histogram
        #print len(histogram)

        im2 = Image.new("P", image.size, 255)
        temp = {}

        for x in range(image.size[1]):
          for y in range(image.size[0]):
            pix = image.getpixel((y,x))
            temp[pix] = pix
            if pix == TEST_TEXT_COLOR:
                im2.putpixel((y,x),0)

        im2.save("output.gif")

        letters = self.get_letters_coordinates(im2)

        v = VectorCompare()

        iconset = ['0','1','2','3','4','5','6','7','8','9','0','a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z']

        imageset = []

        for letter in iconset:
          for img in os.listdir('Letters/%s/'%(letter)):
            temp = []
            if img != "Thumbs.db":
              temp.append(v.buildvector(Image.open("Letters/%s/%s"%(letter,img))))
            imageset.append({letter:temp})

        count = 0
        res = ""
        for letter in letters:
            im3 = im2.crop(( letter[0] , 0, letter[1],im2.size[1] ))
            guess = []

            for image in imageset:
                for x,y in image.iteritems():
                    if len(y) != 0:
                        guess.append( ( v.relation(y[0], v.buildvector(im3)),x) )

            guess.sort(reverse=True)
            res += guess[0][1]
            # Для отладки распознавания
            #print "", guess[0]
            count += 1
        return res



    def get_letters_coordinates(self, im):
        inletter = False
        foundletter=False
        start = 0
        end = 0

        letters = []

        for y in range(im.size[0]): # slice across
          for x in range(im.size[1]): # slice down
            pix = im.getpixel((y,x))
            if pix != WHITE_COLOR:
              inletter = True
          if foundletter == False and inletter == True:
            foundletter = True
            start = y

          if foundletter == True and inletter == False:
            foundletter = False
            end = y
            letters.append((start,end))

          inletter=False
        #print "letters:", letters
        return letters


def create_symbols_images():
    #нарезка символов обучающего множества
    recognizer = ImageRecognizer()
    im = Image.open("output.gif")
    print im.format, im.size, im.mode

    letters = recognizer.get_letters_coordinates(im)

    count = 0
    for letter in letters:
        m = hashlib.md5()
        im2 = im.crop(( letter[0] , 0, letter[1],im.size[1] ))
        m.update("%s%s"%(time.time(),count))
        im2.save("Letters/%s.gif" % (m.hexdigest()))
        count += 1


def main():
    create_symbols_images()



if __name__ == '__main__':
    main()
